<template>
		   <NavBar></NavBar>
	<view class="edit-order-page">
		<u-loading-popup v-if="show_loading" v-model="show_loading" mode="circle" text="加载中..." />
		<!-- 号主预留信息模态框 -->
		<u-popup 
			v-model="ownerInfoModalShow" 
			mode="center" 
			width="600rpx" 
			radius="16rpx"
			:closeable="true"
			close-icon-size="40rpx"
		>
			<view class="owner-info-modal">
				<view class="modal-title">号主预留信息</view>
				<view class="modal-content" v-if="ownerInfoLoading">
					<u-loading mode="circle" size="40rpx" text="加载中..."></u-loading>
				</view>
				<view class="modal-content" v-else-if="ownerInfoData">
					<view class="info-item">
						<text class="info-label">游戏账号：</text>
						<text class="info-value">{{ ownerInfoData.GameAcc }}</text>
					</view>
					<view class="info-item">
						<text class="info-label">游戏密码：</text>
						<view class="password-container">
							<text class="info-value password-text">{{ hiddenPassword }}</text>
							<u-button 
								size="small"
								@click="togglePasswordVisible"
								type="primary"
								plain
								style="margin-left: 20rpx; padding: 8rpx 16rpx;"
							>
								{{ passwordVisible ? '隐藏' : '显示' }}
							</u-button>
							<u-button 
								size="small"
								@click="copyPassword"
								type="info"
								plain
								style="margin-left: 20rpx; padding: 8rpx 16rpx;"
							>
								复制
							</u-button>
						</view>
					</view>
					<view class="info-item">
						<text class="info-label">手机号：</text>
						<text class="info-value">{{ ownerInfoData.GameMobile }}</text>
					</view>
					<view class="info-item">
						<text class="info-label">角色名：</text>
						<text class="info-value">{{ ownerInfoData.Actor || '' }}</text>
					</view>
					<view class="info-item">
						<text class="info-label">游戏名称：</text>
						<text class="info-value">{{ ownerInfoData.Game }}</text>
					</view>
					<view class="info-item">
						<text class="info-label">游戏区服：</text>
						<text class="info-value">{{ ownerInfoData.Zone }}</text>
					</view>
					<view class="info-item">
						<text class="info-label">标题：</text>
						<text class="info-value">{{ ownerInfoData.Title }}</text>
					</view>
				</view>
				<view class="modal-content" v-else>
					<text class="empty-text">暂无号主预留信息</text>
				</view>
				<view class="modal-footer">
					<u-button 
						size="medium"
						@click="copyAllInfo"
						type="success"
						plain
						style="width: 48%; margin-right: 2%;"
					>
						复制号主信息
					</u-button>
					<u-button 
						size="medium"
						@click="ownerInfoModalShow = false"
						type="primary"
						style="width: 48%; margin-left: 2%;"
					>
						关闭
					</u-button>
				</view>
			</view>
		</u-popup>
		<view v-if="!show_loading" class="edit-order-container">
		<!-- 用户信息展示区域 -->
		<view class="account-info-section">
			<view class="section-title">账号信息</view>
			<view class="info-grid">
				<view class="info-item">
					<text class="info-label">手机号：</text>
					<text class="info-value">{{ order_item.account.phone || '-' }}</text>
				</view>
				<view class="info-item">
					<text class="info-label">用户名：</text>
					<text class="info-value" @click="uni.navigateTo({
						url: '/pages/account_platform/account_platform?account_id=' + order_item.account.account_id
					})">{{ order_item.account.username || '-' }}</text>
				</view>
				<view class="info-item">
					<text class="info-label">余额：</text>
					<text class="info-value balance-text">{{ order_item.account.balance || '0.00' }}</text>
				</view>
			</view>
		</view>
		
		<u-form :model="order_item" ref="uFormRef" label-position="top">
			<!-- 基本信息 -->
			<view class="section-title">基本信息</view>
			<u-form-item label="标题">
				<u-textarea border="bottom" disabled  maxlength="-1" v-model="order_item.order_name" placeholder="请输入订单标题" rows="4" />
				</u-form-item>
			<u-form-item label="来源平台"><u-input v-model="order_item.order_source_name" disabled placeholder="请输入来源平台" /></u-form-item>
			<u-form-item label="发布平台"><u-input v-model="order_item.posting_platform_name" disabled placeholder="请输入发布平台" /></u-form-item>
			<u-form-item label="来源订单ID"><u-input v-model="order_item.order_source_id"  placeholder="请输入来源订单ID" disabled /></u-form-item>
			<u-form-item label="发布平台订单ID"><u-input v-model="order_item.posting_platform_id" disabled placeholder="请输入发布平台订单ID" /></u-form-item>
			<u-form-item label="游戏服务器"><u-input v-model="order_item.receiving_server" disabled placeholder="请输入游戏服务器" /></u-form-item>
			
			<!-- 价格信息 -->
			<view class="section-title">价格信息</view>
			<u-form-item label="接单价格"><u-input v-model="order_item.receiving_price" placeholder="请输入接单价格" type="number" step="0.01" /></u-form-item>
			<u-form-item label="接单保证金"><u-input v-model="order_item.receiving_margin" placeholder="请输入接单保证金" type="number" step="0.01" /></u-form-item>
			<u-form-item label="接单效率费"><u-input v-model="order_item.receiving_efficiency_fee" placeholder="请输入接单效率费" type="number" step="0.01" /></u-form-item>
			<u-form-item label="发单价格"><u-input v-model="order_item.posting_price" placeholder="请输入发单价格" type="number" step="0.01" /></u-form-item>
			<u-form-item label="发单保证金"><u-input v-model="order_item.posting_security_fee" placeholder="请输入发单保证金" type="number" step="0.01" /></u-form-item>
			<u-form-item label="发单效率费"><u-input v-model="order_item.posting_efficiency_fee" placeholder="请输入发单效率费" type="number" step="0.01" /></u-form-item>
			<u-form-item label="完成利润"><u-input v-model="order_item.completed_profit" placeholder="请输入完成利润" type="number" step="0.01" /></u-form-item>
			
			<!-- 时间信息 -->
			<view class="section-title">时间信息</view>
			<u-form-item label="接单交付时间"><u-input disabled  v-model="order_item.receiving_delivery_time" placeholder="请输入接单交付时间" type="number" /></u-form-item>
			<u-form-item label="创建时间"><u-input v-model="order_item.create_time" placeholder="请输入创建时间" disabled /></u-form-item>
			<u-form-item label="更新时间"><u-input v-model="order_item.update_time" placeholder="请输入更新时间" disabled /></u-form-item>
			
			<!-- 其他信息 -->
			<view class="section-title">其他信息</view>
			<u-radio-group v-model="order_item_status_value" class="status-radio-group">
				<u-radio 
					@change="order_item_status_radioChange" 
					v-for="(item, index) in order_item_status_list" :key="index" 
					:name="item.value"
					:disabled="item.disabled"
				shape="square">
					{{item.name}}
				</u-radio>
			</u-radio-group>
			<u-form-item label="号主联系方式"><u-input v-model="order_item.owner_contact" placeholder="请输入号主联系方式" /></u-form-item>
			<u-form-item label="代练联系方式"><u-input v-model="order_item.dailian_contact" placeholder="请输入代练联系方式" /></u-form-item>
			<u-form-item label="备注">
				<u-textarea maxlength="-1" v-model="order_item.remark" placeholder="请输入备注信息" rows="4" />
			</u-form-item>
			<view style="display: flex; justify-content: flex-end;">
				<u-button size="medium" :loading="but_loading" @click="one_submitOrder(false)" type="primary">提交</u-button>
			<u-button @click="showOwnerContactInfo" type="info" size="medium">号主预留信息</u-button>
			</view>
		</u-form>
	</view>
	</view>

	 <u-fab direction="left" ref="fabRef"  draggable :autoStick="false" >
      <u-button @click="onBtnClick_script">话题库</u-button>
	 </u-fab>

	 <u-modal title="请确认利润是否正确填写" @confirm="one_submitOrder(true)" show-cancel-button v-model="complete_profit_model" content="完成利润是否正确?"></u-modal>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app'
import { getOrderDetail, getOrderStatusList, updateOrder, getOrderOwnerInfo } from '@/static/apis/wzry.js'
import { defineProps } from 'vue';
import { isEqual } from '@/static/js/hub'

const order_item = ref({});
// 描述
const remark = ref('');
const show_loading = ref(true);
// 用户信息
const userInfo = ref({});

const uFormRef = ref();

const but_loading = ref(false)

const order_item_status_list = ref([])
// 号主预留信息模态框相关状态
const ownerInfoModalShow = ref(false)
const ownerInfoData = ref(null)
const ownerInfoLoading = ref(false)
const passwordVisible = ref(false)
const hiddenPassword = ref('')
const order_item_status_value = ref(null)
const fabRef = ref(null);
const complete_profit_model = ref(false)
async function getOrderStatusListAsync() {
	const res = await getOrderStatusList();
	if (res.code === 0) {
		order_item_status_list.value = res.data;
		// 如果已有订单数据，设置对应的状态值
		
		if (order_item.value && order_item.value.status) {
			order_item_status_value.value = order_item.value.status.code;
		}
		show_loading.value = false;
	} else {
		uni.showToast({
			title: res.message || '获取订单状态列表失败',
			icon: 'none',
			duration: 2000
		});
	}
}

function onBtnClick_script() {
	console.log("跳转到话题库");
uni.navigateTo({
	url: '/pages/script/script'
});
	
}

// 声明接收 orderID
const props = defineProps({
  orderID: {
    type: String,
    required: true
  }
});




// 加载订单详情
onLoad(async (options) => {
	const orderID = options.orderID;
	if (!orderID) {
		uni.showToast({
			title: '订单ID不存在',
			icon: 'none',
			duration: 2000
		});
		return;
	}
	try {
		const res = await getOrderDetail({
			order_id: orderID
		});
		if (res.code === 0) {
			order_item.value = res.data;
			// 描述
			remark.value = order_item.value.remark || '';
			// 从API响应中获取用户信息
			if (res.user_id) {
				userInfo.value = {
					user_id: res.user_id,
					username: res.username,
					balance: res.balance
				};
			}
			await getOrderStatusListAsync();
			console.log(order_item.value);
		} else {
			uni.showToast({
				title: res.message || '获取订单详情失败',
				icon: 'none',
				duration: 2000
			});
			show_loading.value = false;
		}
	} catch (error) {
		uni.showToast({
			title: '获取订单详情失败',
			icon: 'none',
			duration: 2000
		});
		show_loading.value = false;
	}
});

function order_item_status_radioChange(e) {
	console.log('状态变化:', e);
	// 更新订单状态
	order_item.value.status = {
		code: e.value,
		message: order_item_status_list.value.find(item => item.code === e.value)?.message || ''
	};
}
// 一次确认
function one_submitOrder(value) {
	let submitData = {
		...order_item.value
	}
	
	if(value === false) {
		// 把 completed_profit 转换成数字并且保留2位小数
			submitData.completed_profit = Number(parseFloat(submitData.completed_profit).toFixed(2));
			// 判断完成利润如果是0元需要警告
			if (submitData.completed_profit <= 0) {
				complete_profit_model.value = true;
				return;
			}else {
				submitOrder(submitData);
			}
	} else {
		submitOrder(submitData);
	}
	
}
function submitOrder(submitData) {
	console.log(submitData.remark, remark.value);
	// 如果新增了描述，需要在原有描述基础上追加
	if (isEqual(submitData.remark, remark.value) == false && submitData.remark != null) {
		// 删除submitData.remark中和remark.value相同的部分
		submitData.remark = submitData.remark.replace(remark.value, '');
	} 
	
	submitData.status = order_item_status_value.value;
	submitData.completed_profit = Number(submitData.completed_profit)
	const keysToDelete = ["update_time", "create_time",  "posting_platform_id", "order_source_id"]
	keysToDelete.forEach(key => {
		delete submitData[key];
	});

	but_loading.value = true;
	updateOrder(submitData).then(res => {
		if (res.code === 0) {
			uni.showToast({
				title: '更新订单成功',
				icon: 'success',
				duration: 2000
			});
			uni.navigateBack({
				delta: 1
			});
		} else {
			uni.showToast({
				title: res.message || '更新订单失败',
				icon: 'none',
				duration: 2000
			});
		}
	}).finally(() => {
		but_loading.value = false;
	});
	
}
// 号主预留信息
function showOwnerContactInfo() {
	if (!order_item.value.order_source_id) {
		uni.showToast({
			title: '获取号主信息失败：订单ID不存在',
			icon: 'none',
			duration: 2000
		});
		return;
	}
	
	ownerInfoModalShow.value = true;
	ownerInfoLoading.value = true;
	ownerInfoData.value = null;
	
	getOrderOwnerInfo({
		OrderID: order_item.value.order_source_id
	}).then(res => {
		if (res.code === 0 && res.data) {
			ownerInfoData.value = res.data;
			// 初始化密码显示
			hiddenPassword.value = hidePassword(res.data.GamePass || '');
		} else {
			uni.showToast({
				title: res.message || '获取号主预留信息失败',
				icon: 'none',
				duration: 2000
			});
		}
	}).catch(error => {
		console.error('获取号主信息失败:', error);
		uni.showToast({
			title: '获取号主预留信息失败，请重试',
			icon: 'none',
			duration: 2000
		});
	}).finally(() => {
		ownerInfoLoading.value = false;
	});
}

// 密码隐藏处理
function hidePassword(password) {
	if (!password) return '';
	if (password.length <= 4) return password.replace(/./g, '*');
	return password.slice(0, 1) + password.slice(1, -1).replace(/./g, '*') + password.slice(-1);
}

// 切换密码可见性
function togglePasswordVisible() {
	passwordVisible.value = !passwordVisible.value;
	if (passwordVisible.value) {
		hiddenPassword.value = ownerInfoData.value?.GamePass || '';
	} else {
		hiddenPassword.value = hidePassword(ownerInfoData.value?.GamePass || '');
	}
}

// 复制密码
function copyPassword() {
	if (!ownerInfoData.value?.GamePass) return;
	
	uni.setClipboardData({
		data: ownerInfoData.value.GamePass,
		success: () => {
			uni.showToast({
				title: '密码已复制',
				icon: 'success',
				duration: 1500
			});
		},
		fail: () => {
			uni.showToast({
				title: '复制失败，请重试',
				icon: 'none',
				duration: 2000
			});
		}
	});
}

// 复制全部号主信息
function copyAllInfo() {
	if (!ownerInfoData.value) return;
	
	const { GameAcc, GamePass, GameMobile, Actor, Game, Zone, Title } = ownerInfoData.value;
	const info = `游戏账号：${GameAcc || ''}
游戏密码：${GamePass || ''}
号主手机号：${GameMobile || ''}
角色名：${Actor || ''}
游戏服：${Game || ''}
游戏服务器：${Zone || ''}
标题：${Title || ''}`;
	
	uni.setClipboardData({
		data: info,
		success: () => {
			uni.showToast({
				title: '信息已复制',
				icon: 'success',
				duration: 1500
			});
		},
		fail: () => {
			uni.showToast({
				title: '复制失败，请重试',
				icon: 'none',
				duration: 2000
			});
		}
	});
}
</script>

<style scoped lang="scss">
.edit-order-container {
	padding: 24rpx;
	background-color: #f5f7fa;
	min-height: 100vh;
}

/* 用户信息区域样式 */
.account-info-section {
	background-color: #ffffff;
	border-radius: 12rpx;
	padding: 24rpx;
	margin-bottom: 30rpx;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.info-grid {
	padding: 16rpx 0;
}

.balance-text {
	color: #f56c6c;
	font-weight: bold;
}

.section-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #323233;
	margin: 32rpx 0 16rpx 0;
	padding-bottom: 8rpx;
	border-bottom: 2rpx solid #2979ff;
}

.status-radio-group {
	display: flex;
	flex-wrap: wrap;
	gap: 24rpx;
	padding: 16rpx;
	background-color: #ffffff;
	border-radius: 8rpx;
	margin-bottom: 24rpx;
}

u-radio {
	margin: 8rpx 0;
}

/* 号主预留信息模态框样式 */
.owner-info-modal {
	padding: 40rpx 30rpx;
	background-color: #fff;
	border-radius: 16rpx;
}

.modal-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #323233;
	text-align: center;
	margin-bottom: 40rpx;
}

.modal-content {
	padding: 20rpx;
	background-color: #f5f7fa;
	border-radius: 8rpx;
	margin-bottom: 30rpx;
}

.info-item {
	display: flex;
	align-items: center;
	margin-bottom: 24rpx;
	flex-wrap: wrap;
}

.info-label {
	font-size: 26rpx;
	color: #606266;
	width: 160rpx;
	text-align: right;
	margin-right: 20rpx;
}

.info-value {
	font-size: 28rpx;
	color: #323233;
	flex: 1;
}

.password-container {
	display: flex;
	align-items: center;
	flex: 1;
}

.password-text {
	font-size: 28rpx;
	color: #323233;
}

.empty-text {
	font-size: 26rpx;
	color: #909399;
	text-align: center;
	padding: 40rpx 0;
}

.modal-footer {
	padding-top: 20rpx;
	border-top: 2rpx solid #ebeef5;
}

/* 响应式设计 */
@media (max-width: 750rpx) {
	.owner-info-modal {
		padding: 30rpx 20rpx;
	}
	
	.modal-title {
		font-size: 28rpx;
		margin-bottom: 30rpx;
	}
	
	.info-item {
		margin-bottom: 20rpx;
	}
	
	.info-label {
		font-size: 24rpx;
		width: 140rpx;
	}
	
	.info-value {
		font-size: 26rpx;
	}
	
	.password-container {
		flex-direction: column;
		align-items: flex-start;
		margin-left: 160rpx;
		margin-top: 10rpx;
	}
	
	.password-container u-button {
		margin-left: 0;
		margin-right: 10rpx;
		margin-bottom: 10rpx;
	}
}
</style>
